<script setup lang='ts'>
  import { reactive, ref, nextTick } from 'vue';
  import { roleApi } from '@/api/controller' 
  import { ToastSuccess, Toastloading } from '@/utils/public';
  const $emit = defineEmits(['updateList'])
  const formLabelWidth = '80px'
  const dataForm = ref();
  const action = reactive({
    dialogFormVisible:false,
    permission:[] as any[],
    defaultCheckedKeys:[] as any[],
  })
  const form = reactive({
    id:'',
    name:'',
    desc:'',
  })
  const formRules = {
    name: [{ required: true, trigger: 'blur', message: '角色不可为空' }],
    desc: [{ required: true, trigger: 'blur', message: '描述不可为空' }]
  }
  const handleSubmit = ()=>{
    dataForm.value.validate(async(valid: any)=>{
      if(valid) {
        const loading = Toastloading();
        if(form.id) {
          await roleApi.updateRole(form.id,form)
          ToastSuccess('修改成功')
          
        }else {
          await roleApi.addRole(form)
          ToastSuccess('新增成功')
        }
        loading.close();
        closeDialog();
        $emit('updateList')
      }
    })
  }
  const openDialog = (row={})=> {
    Object.assign(form,row)
    action.dialogFormVisible = true
  }
  const closeDialog = ()=>{
    Object.assign(form,{
      id:'',
      name:'',
      desc:'',
    })
    nextTick(() => {
      dataForm.value.clearValidate();
    });
    action.dialogFormVisible = false
  }
  defineExpose({
    openDialog
  })
</script>

<template>
  <div>
    <el-dialog
    top="5vh"
    class="input-width"
    v-model="action.dialogFormVisible"
    :close-on-click-modal="false"
    :show-close="false"
    :close-on-press-escape="false"
    :title="form.id?'修改角色':'新增角色'">
      <el-form ref="dataForm" :model="form" :rules="formRules">
        <el-form-item :label-width="formLabelWidth" label="角色" prop="name">
          <el-input v-model="form.name" auto-complete="off"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="角色描述" prop="desc">
          <el-input v-model="form.desc" auto-complete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="handleSubmit()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>